require('../../css/jeui/skin/jebox.css');
require('./index.less');
import $ from 'jquery';
import qrcode from '../lib/jquery.qrcode.min'
var userbase = {};
//接口列表
var ticket_list_data = { "id": "1", "jsonrpc": "2.0", "method": "getGroupTicketTypes", "params": {} };
var pay_data = {};
var ticketdata = $.ajax({
    type: "post",
    contentType: "application/json;charset=utf-8",
    url: "/api/ticketApi",
    dataType: "json",
    data: JSON.stringify(ticket_list_data),
});
ticketdata.then(function(res) {
    for (var i = 0; i < res.result.body.length; i++) {
        var ticket_list_html = $("#ticket_list").html();
        var tdata = res.result.body[i];
        tdata.price = getprice(res.result.body[i].price)
        var conReg = /(?:\{)(\w*)(?:\})/g;
        var source = ticket_list_html.replace(conReg, function(node, key) {
            return tdata[key];
        });
        if (res.result.body[i].price == undefined) {
            $(".push-select").attr('disabled', "true")
        }
        $(".ticket_list").append(source);

    }
    var ticket_buy_html = $("#button-box").html();
    // var conReg = /(?:\{)(\w*)(?:\})/g;
    // var source_buy = ticket_buy_html.replace(conReg, function(node, key) {
    //     return tdata[key];
    // });
    $(".button-box").append(ticket_buy_html);
    var button = $(".push-select");
    for (var s = 0; s < button.length; s++) {
        (function(s) {
            button[s].onclick = function() {
                var ticket_choice_html = $("#ticket_choice").html();
                var chdata = {}
                chdata.code = $(this).parent().prevAll(".code").html();
                chdata.name = $(this).parent().prevAll(".name").html();
                chdata.price = $(this).parent().prevAll(".price").html();
                chdata.id = $(this).parent().prevAll(".id").html()
                chdata.number = "1";
                var conReg = /(?:\{)(\w*)(?:\})/g;
                var source = ticket_choice_html.replace(conReg, function(node, key) {
                    return chdata[key];
                });
                if ($(".ticket_choice").children("tr.ticket_" + chdata.id).length == "0") {
                    if (chdata.code == "etp") {
                        $(".ticket_choice").show().append(source);
                        $(".etp").children(".nameid").html("");
                    } else {
                        $(".ticket_choice").show().append(source);
                    }
                } else if ($(".ticket_choice").children("tr.ticket_" + chdata.id).length > "0") {
                    if (chdata.code == "etp") {
                        document.getElementById("number_2").innerHTML++;
                    } else {
                        document.getElementById("number_" + chdata.id + "").innerHTML++
                    }
                };
                var p = chdata.price;
                var n = $("#number_" + chdata.id).html();
                var priceAll = p * n;
                if (p == "暂无票价") {
                    $("#amount_" + chdata.id).val("0");
                } else {
                    $("#amount_" + chdata.id).val(priceAll);
                }
                if ($(".ticket_choice").children("tr").length != "0") {
                    $("#remove_id").removeAttr("disabled");
                    $("#input_id").removeAttr("disabled");
                };
                $("#remove_id").click(function() {
                    $('input:checkbox').each(function() {
                        if ($(this).is(':checked') == true) {
                            $(this).parents("tr").remove();
                            if ($(".ticket_choice").children("tr").length == "0") {
                                $("#remove_id").attr('disabled', "true");
                            };
                            if ($(this).val() == "crp") {
                                $("#input_id").attr('disabled', "true");
                            }
                        }
                    });

                })


            }

        })(s);

    }

    $("#input_id").click(function() {
        realname();
    });
    $(".pay-ticket").click(function() {
        add_ticket_table();

    });

})

function toDecimal(num) {
    return num = num.toFixed(2)
}

function add_ticket_table() {
    var temp_html = "<table class='je-table'><thead><tr><td>票型</td><td>购买数量</td><td>金额</td></tr></thead><tbody class='ticket-info'></tbody></table><div class='je-form-item'>合计购买数量:<span class='numall'></span></div><div class='je-form-item'>应付金额:￥<span class='priceall'></span><div class='realbota'><input type='button' class='org_btn' id='paymoney' value='确认收费'></div></div>";
    jeBox.open({
        title: "确认出票",
        boxSize: ['60%', '40%'],
        content: temp_html,
        maskClose: false,
        closefun: function(index, id) {
            window.location.reload();
        }
    })
    var titemhtml = $("#ticket-info").html();
    var number_arr = [];
    var amount_arr = [];
    for (var i = 0; i < $(".ticket_choice tr").length; i++) {
        var tinfodata = {}
        tinfodata.id = $(".ticket_choice tr:eq(" + i + ") td:eq(0)").children("input").val();
        tinfodata.name = $(".ticket_choice tr:eq(" + i + ") td:eq(2)").children(".ticketname").val();
        tinfodata.number = $(".ticket_choice tr:eq(" + i + ") td:eq(4)").html();
        tinfodata.amount = $(".ticket_choice tr:eq(" + i + ") td:eq(5)").children(".amount").val();
        var conReg = /(?:\{)(\w*)(?:\})/g;
        var source = titemhtml.replace(conReg, function(node, key) {
            return tinfodata[key];
        });
        $(".ticket-info").append(source);
        number_arr.push(tinfodata.number);
        amount_arr.push(tinfodata.amount);
    }
    number_arr.forEach(function(item, index) {
        number_arr[index] = +item;
    });
    amount_arr.forEach(function(item, index) {
        amount_arr[index] = +item;
    });
    // console.log(number_arr[0] + ">>>")
    // console.log(amount_arr + ">>>>>")
    $(".numall").html(sum(number_arr));
    $(".priceall").html(toDecimal(sum(amount_arr)));
    $("#paymoney").click(function() {
        var pay = {}
        pay.numall = sum(number_arr);
        pay.priceall = toDecimal(sum(amount_arr));
        pay.peice = $(".priceall").html();
        pay.change = 0;
        var pay_html = "<div><div class='je-form-item'><label class='je-label je-f14'>总金额</label><div class='je-inputbox'><input type='text' name='title' autocomplete='off' class='je-input pay_money' readonly='readonly' value='" + pay.peice + "'></div></div><div class='je-form-item'><label class='je-label je-f14'>现金支付</label><div class='je-inputbox'><input type='number' name='title' autocomplete='off' value='" + pay.peice + "' class='je-input cash_money' min='0'></div></div><div class='je-form-item'><label class='je-label je-f14'>找零</label><div class='je-inputbox'><input type='text' name='title' autocomplete='off' value='" + pay.change + "' readonly='readonly' class='je-input change_money'></div></div></div>"
        var order_array = [];
        for (var t = 0; t < $(".ticket-info tr").length; t++) {
            var arr = {}
            arr.groupTicketId = $(".ticket-info tr:eq(" + t + ") td:eq(0)").html();
            arr.price = $(".ticket-info tr:eq(" + t + ") td:eq(3)").html();
            arr.number = $(".ticket-info tr:eq(" + t + ") td:eq(2)").html();
            console.log(arr)
            order_array.push(arr)
        }
        console.log(order_array)
        var pay_json = { "id": "1", "jsonrpc": "2.0", "method": "confirmSettlement", "params": { "order": { "sellerId": "1", "customerType": "1", "transactionTypeId": "1", "ifBooked": "0", "orderType": "0", "saleTypeId": "1", "ticketName": "", "number": pay.numall, "amount": pay.priceall, "state": "", "isDel": "0", "waterFlow": [{ "type": "1", "paymentTypeId": "0" }], "orderDetail": order_array, "settleState": "1", "source": "", "playdate": "" } } }
        console.log(pay_json)
        var paydata = $.ajax({
            type: "post",
            contentType: "application/json;charset=utf-8",
            url: "/api/ticketApi",
            dataType: "json",
            data: JSON.stringify(pay_json),
        });
        jeBox.open({
            title: "付款",
            boxSize: ['60%', '40%'],
            content: pay_html,
            maskClose: false,
            button: [{
                name: "确认收款",
                callback: function() {
                    paydata.then(function(data) {
                        if (data.result.code == 200) {
                            var ticket_code_html = $("#Ticket_temp").html()
                            for (var i = 0; i < data.result.body.orderDetail.length; i++) {
                                var codedata = data.result.body.orderDetail[i];
                                codedata.createTime = data.result.body.orderDetail[i].validateDate
                                codedata.valiTime = getvalitime(data.result.body.orderDetail[i].validateDate, data.result.body.orderDetail[i].validateDays)
                                codedata.ticket = data.result.body.orderDetail[i].code
                                codedata.price = tinfodata.amount
                                var conReg = /(?:\{)(\w*)(?:\})/g;
                                var source = ticket_code_html.replace(conReg, function(node, key) {
                                    return codedata[key];
                                });
                                $(".Ticket_temp").append(source)
                                    // console.log($("#code_" + codedata.id).html())
                                $("#code_" + codedata.id).qrcode({
                                    render: "table",
                                    width: 120,
                                    height: 120,
                                    text: codedata.id
                                })

                            }
                            $("#ticket_02").hide()
                            var temp_html = $("#ticket_02").html();
                            jeBox.open({
                                title: '打印票据',
                                boxSize: ["600px", "480px"],
                                content: temp_html,
                                maskLock: false,
                                btnAlign: "center",
                                button: [{
                                    name: '预览并打印',
                                    callback: function() {
                                        var LODOP;
                                        LODOP = getLodop();
                                        LODOP.PRINT_INIT("print_ticket");
                                        LODOP.ADD_PRINT_HTM("5.0mm", "5.0mm", "170mm", "80mm", $("#ticket_02").html());
                                        LODOP.PRINT_DESIGN()

                                    }
                                }],
                                closefun: function(index, id) {
                                    window.location.reload();
                                }
                            })
                        }
                    })
                }
            }],
            closefun: function(index, id) {
                window.location.reload();
            }
        });
        $(".cash_money").bind('input propertychange', function() {
            $(".change_money").val($(this).val() - pay.peice);
            $(".cash_money").keyup(function() {
                var reg = $(this).val().match(/\d+\.?\d{0,2}/);
                var txt = '';
                if (reg != null) {
                    txt = reg[0];
                }
                $(this).val(txt);
            }).change(function() {
                $(this).keypress();
                var v = $(this).val();
                if (/\.$/.test(v)) {
                    $(this).val(v.substr(0, v.length - 1));
                }
            });
        });
    })
}

function getprice(price) {
    if (price == undefined) {
        return "暂无票价"
    } else {
        return price;
    }
}

function getname(n) {
    if (n == null) {
        return "散票"
    } else {
        return n;
    }
}

function sum(arr) {
    var s = 0;
    if (arr.length == 0) {
        return 0;
    } else if (arr.length == 1) {
        return arr[0];
    } else {
        for (var i = 0; i < arr.length; i++) {
            s += arr[i];
        }
        return s;
    }
}

function getmoney(a) {
    var cash = $(".cash_money");
    cash.bind('input propertychange', function() {
        $('.change_money').val($(this).val());
    });
    // return cash - a;
}
var defreg = {
    "img": /(\.|\/)(gif|jpe?g|png)$/i,
    "doc": /(\.|\/)(pdf|doc|docx|ppt|pptx)$/i,
    "mobile": /^0?(13|15|18|14|17)[0-9]{9}$/,
    "email": /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/,
    "emailmobile": /^1\d{10}$|^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/,
    "password": /^[^\u4E00-\u9FA5\uF900-\uFA2D\u0020]{6,16}$/,
    "loginname": /^[^\u4E00-\u9FA5\uF900-\uFA2D\u0020]{26}$/,
    //"password":/^[0-9a-zA-Z]{8,16}$/,
    "url": /((https|http|ftp|rtsp|mms):\/\/)?(([0-9a-z_!~*'().&=+$%-]+:)?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)/g,
    "mobilecode": /^\d{6}$/,
    "yaocode": /^\d{6}$/,
    "realname": /^[\u4e00-\u9fa5]{2,5}$/i,
    "amount": /^[0-9]+([.]{1}[0-9]{1,2})?$/,
    "vcode": /^\w{4}$/
};
$.fn.inputtips = function(params) {
    var $this = $(this);
    if ($this.length == 0) {
        return;
    };
    var params = $.extend({
        left: 0,
        top: 40,
        reg: null,
        callback: null
    }, params);
    var $this = $(this);
    var $dis = null;
    var focus_text = $this.data("focus");
    var error_text = $this.data("error");
    var error_empty = $this.data("empty");
    var init = function() {
        if (!$this.siblings(".inputtips").length) {
            $dis = $("<div class='inputtips'></div>");
            $dis.insertAfter($this);
            $dis.css({
                'left': params.left + 'px',
                'top': params.top + 'px'
            })
        } else {
            $dis = $this.siblings(".infodis").empty();
        }
    }
    var bclear = function() {
        $this.removeClass("error").removeClass("focus");
        $dis.removeClass("error").removeClass("focus").empty();
    }
    $this.on('focus', function() {
        bclear();
        $this.addClass("focus");
        $dis.addClass("focus");
        $dis.html(focus_text);
    });
    $this.on('blur', function() {
        var istr = $this.val();
        bclear();
        if (error_empty == "" && istr == "") { //元素可为空且输入为空
            bclear();
            $this.data("verify", "true");
            return
        }
        if (error_empty != "" && istr == "") { //元素不能为空而输入为空
            bclear();
            $this.data("verify", "flase");
            $dis.addClass("error");
            $dis.html(error_empty);
            return
        }
        if (params.reg && !defcheck(istr, params.reg)) {
            bclear();
            $this.data("verify", "flase");
            $dis.addClass("error");
            $dis.html(error_text);
            return
        }
        if (params.reg && defcheck(istr, params.reg) && params.callback) {
            bclear();
            d = params.callback($this.val());
            if (d.statu) {
                $this.data("verify", "true");
            } else {
                $dis.html(d.msg);
                $dis.addClass("error");
            }
            return
        }
        if (!params.reg && !params.callback) {
            bclear();
            $this.data("verify", "true");
            return
        }
        if (!params.reg && params.callback) {
            bclear();
            d = params.callback($this.val());
            if (d.statu) {
                $this.data("verify", "true");
            } else {
                $dis.html(d.msg);
                $dis.addClass("error");
            }
            return
        }
        $this.data("verify", "true");
    });
    $this.bind('view.disinfo', function(event, info) {
        bclear();
        $dis.addClass("error");
        $dis.html(info)
    });
    init();
};

function getsum(a, b) {
    return a + b;
}

function getvalitime(v, d) {
    return parseInt(v) + parseInt(d)
}

function formattime(date) {
    return date.substr(0, 10);
}

function defcheck(str, f) {
    if (defreg.hasOwnProperty(f) && defreg[f].test(str)) {
        return true;
    } else {
        return false;
    }
}

function checkidcard(str) {
    var temp = {};
    if (id_cards.checkCard(str)) {
        temp.msg = "";
        temp.statu = true;
        return temp;
    } else {
        temp.msg = "身份证号格式不正确";
        temp.statu = false;
        return temp;
    }
}

//身份证号码
var id_cards = {
    cities: {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外"
    },
    checkCard: function(a) {
        return this.isCardNo(a) && this.checkProvince(a) && this.checkBirthday(a) && this.checkParity(a)
    },
    isCardNo: function(a) {
        var b = /(^\d{15}$)|(^\d{17}(\d|X)$)/i;
        return b.test(a)
    },
    checkProvince: function(a) {
        var b = a.substr(0, 2);
        return void 0 == this.cities[b] ? !1 : !0
    },
    checkBirthday: function(a) {
        var b = a.length;
        if ("15" == b) {
            var c = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/,
                d = a.match(c),
                e = d[2],
                f = d[3],
                g = d[4],
                h = new Date("19" + e + "/" + f + "/" + g);
            return this.verifyBirthday("19" + e, f, g, h)
        }
        if ("18" == b) {
            var i = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/i,
                d = a.match(i),
                e = d[2],
                f = d[3],
                g = d[4],
                h = new Date(e + "/" + f + "/" + g);
            return this.verifyBirthday(e, f, g, h)
        }
        return !1
    },
    checkParity: function(a) {
        var b = a.length;
        if ("18" == b) {
            var c, d, e = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2),
                f = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"),
                g = 0;
            for (c = 0; 17 > c; c++) g += a.substr(c, 1) * e[c];
            return d = f[g % 11],
                d == a.substr(17, 1).toUpperCase() ? !0 : !1
        }
        return !0
    },
    verifyBirthday: function(a, b, c, d) {
        var e = new Date,
            f = e.getFullYear();
        if (d.getFullYear() == a && d.getMonth() + 1 == b && d.getDate() == c) {
            var g = f - a;
            return g >= 0 && 120 >= g ? !0 : !1
        }
        return !1
    }
};

var realname = function(donefun, failfun) {
    var temp_html = "<div class='realnwarp bosshow'><div class='realncom'><div class='realitem'><div class='realtit'>真实姓名</div><div class='relinright'><input autocomplete='off' class='realcinput' type='text' id='trun_name' name='trun_name' data-focus = '请输入真实姓名' data-error = '真实姓名格式错误' data-empty = '真实姓名不能为空' placeholder='请输入真实姓名' maxlength='10'></div></div><div class='realitem'><div class='realtit'>身份证号</div><div class='relinright'><input autocomplete='off' class='realcinput' type='text' id='trun_card' name='trun_card' data-focus = '请输入身份证号码' data-error = '身份证号码格式错误' data-empty = '身份证号码不能为空' placeholder='请输入身份证号码' maxlength='18'></div></div><div class='realmiaoshu'></div><div class='realbota'></div></div></div>"
    jeBox.open({
        title: "实名认证",
        boxSize: ["440px", '35%'],
        content: temp_html,
        button: [{
                name: "提交信息",
                callback: function(eobj) {
                    $("#trun_name").inputtips({
                        left: 0,
                        top: 40,
                        reg: "realname",
                        callback: null
                    });
                    $("#trun_card").inputtips({
                        left: 0,
                        top: 42,
                        reg: null,
                        callback: null
                    });

                    $('#trun_name').add("#trun_card").trigger('blur');
                    if (($('#trun_name').data("verify") == "true") && ($('#trun_card').data("verify") == "true")) {
                        var real_json_data = { "id": "1", "jsonrpc": "2.0", "method": "addTouristIdentity", "params": { "tourist": { "name": $.trim($("#trun_name").val()), "identity": $.trim($("#trun_card").val()) } } };
                        var realdata = $.ajax({
                            type: "post",
                            contentType: "application/json;charset=utf-8",
                            url: "/api/ticketApi",
                            dataType: "json",
                            data: JSON.stringify(real_json_data),
                        });
                        realdata.done(function(res) {
                            console.log(res.result.code)
                            if (res.result.code == 200) {
                                jeBox.closeAll('dialog');
                                jeBox.msg('身份信息提交成功', { icon: 7 });
                                $(".nameid").html("已实名认证");

                            } else {
                                jeBox.closeAll('dialog');
                                jeBox.msg('信息提交失败,请稍后再试!', { icon: 6 });

                            }
                        })
                        realdata.fail(function() {
                            jeBox.closeAll('dialog');
                            jeBox.msg("系统异常，请刷新重试", { icon: 6 })
                        });

                    }
                    // })
                }
            },
            {
                name: "取消"
            }
        ]
    });
};